from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@127.0.0.1:3306/f1"
# 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# 绑定app至SQLAlchemy
db = SQLAlchemy(app)

tags = db.Table('post_tag',
    db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('posts.id'))
)

# 文章
class Posts(db.Model):
   id = db.Column(db.Integer,primary_key=True)
   title = db.Column(db.String(255))
   tags = db.relationship("Tags",secondary=tags,backref='Posts')

# 标签
class Tags(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(50))


if __name__ == "__main__":
    pass
    # 生成表
   # db.create_all()
    

   
  # 创建文章
    # p1 = Posts(title='flask')
    # p2 = Posts(title='django')
    # p3 = Posts(title='python')



  # 创建标签
    # t1 = Tags(name='f')
    # t2 = Tags(name='g')
    # t3 = Tags(name='p')

  # 添加数据
    # p1.tags = [t1,t2]
    # p3.tags = [t1,t3]
    # p2.tags = [t3,t2]

    # db.session.add(p1)
    # db.session.add(p2)
    # db.session.add(p3)
    # db.session.commit()



  # 根据文章查标签

    # p = db.session.query(Posts).first()
    # print(111111,p,1111111)
    # print(2222222,p.title,2222222)
    # print(333333333,p.tags,33333333)

  # 根据标签查文章
    # t = db.session.query(Tags).get(2)
    # print(11111111111,t,111111111111)
    # print(22222222222,t.name,222222222222)
    # print(33333333333,t.Posts,333333333333)